#include "client.h"
// Plane类的函数定义

// 构造函数
Plane::Plane()
{
    for (int i = 0; i < MAXCNT; i++)
    {
        strcpy(table[i].status, "AVAILABLE");
        strcpy(table[i].seat_num, "");
        strcpy(table[i].passenger_name, "");
    }
}

// 检查座位状态
string Plane::check_seat_status(string seat_num)
{
    // 检查座位号是否越界
    // cout << "checking seat: " << seat_num << endl;
    int row_num = stoi(seat_num.substr(0, seat_num.size() - 1)); // 提取行数
    int col_num = seat_num[seat_num.size() - 1] - 'A';           // 提取列数，并转换为数字

    if (row_num < 1 || row_num > row || col_num < 0 || col_num >= col)
    {
        return "OUT_OF_RANGE"; // 座位越界
    }

    // 检查座位状态
    int i;
    for (i = 0; i < MAXCNT; i++)
    {
        // cout << "query seat : " << string(table[i].seat_num) << endl;
        if (strcmp(table[i].status, "AVAILABLE") && !strcmp(table[i].seat_num, seat_num.data()))
        {
            return string(table[i].passenger_name);
        }
    }
    return "AVAILABLE";
}

// Agent类的函数定义
// 根据实验要求，以下是Agent类的函数定义
// 你可以根据实际需要进行进一步的修改和补充

int find_available_seat_ind(Plane plane)
{
    auto ind = 0;
    for (ind = 0; ind < MAXCNT; ind++)
    {
        if (!strcmp(plane.table[ind].status, "AVAILABLE"))
            break;
    }
    // cout << "got ind " << ind << endl;
    return ind;
}

// 预订座位
string Flights::reserve_seat(Plane &plane, string seat_num, string passenger_name)
{
    // 检查座位是否可预定
    auto seat_status = plane.check_seat_status(seat_num);
    if (seat_status == "OUT_OF_RANGE")
    {
        return "Seat number is out of range."; // 座位号越界
    }
    else if (seat_status != "AVAILABLE")
    {
        return "Seat " + string(seat_num) + " is already occupied."; // 座位已被占用
    }
    // 预定座位
    auto seat_ind = find_available_seat_ind(plane);
    strcpy(plane.table[seat_ind].seat_num, seat_num.data());
    strcpy(plane.table[seat_ind].passenger_name, passenger_name.data());
    strcpy(plane.table[seat_ind].status, "reserve");
    return "Seat " + string(plane.table[seat_ind].seat_num) + " reserved by " + string(plane.table[seat_ind].passenger_name) + " successfully."; // 预定成功
}

int find_seat_num_ind(Plane plane, string seat_num)
{
    int ind = 0;
    for (ind = 0; ind < MAXCNT; ind++)
    {
        if (!strcmp(plane.table[ind].seat_num, seat_num.data()))
            break;
    }
    // printf("find ind:%d", ind);
    return ind;
}

// 售票
string Flights::sell_ticket(Plane &plane, string seat_num, string passenger_name)
{

    // 检查座位状态
    string seat_status = plane.check_seat_status(seat_num);
    if (seat_status == "OUT_OF_RANGE")
    {
        return "Seat number is out of range.";
    }
    else if (seat_status == "AVAILABLE")
    {
        int ind = find_available_seat_ind(plane);
        strcpy(plane.table[ind].passenger_name, passenger_name.data());
        strcpy(plane.table[ind].status, "ticket");
        strcpy(plane.table[ind].seat_num, seat_num.data());
        return "Ticket " + seat_num + " was sold by " + passenger_name + " successfully.";
    }
    else
    {
        int ind = find_seat_num_ind(plane, seat_num);
        // 检查乘客名义预定的座位
        if (strcmp(plane.table[ind].passenger_name, passenger_name.data()) != 0)
        {
            return "This seat " + passenger_name + " is reserved or bought by another passenger.";
        }
        if ((strcmp(plane.table[ind].passenger_name, passenger_name.data()) == 0) && !strcmp(plane.table[ind].status, "ticket"))
        {
            return "Ticket " + seat_num + " have been bought by " + passenger_name + " seconds ago. No need for other action.";
        }
        // 修改座位状态和乘客名单
        strcpy(plane.table[ind].status, "ticket");
        return "Ticket " + seat_num + " was bought by " + passenger_name + " successfully.";
    }

    return "Unknown seat status.";
}

// 取消预订/售票
string Flights::cancel_reservation(Plane &plane, string seat_num, string passenger_name)
{
    // 检查座位状态
    string seat_status = plane.check_seat_status(seat_num);

    if (seat_status == "OUT_OF_RANGE")
    {
        return "Seat is out of range.";
    }
    else if (seat_status == "AVAILABLE")
    {
        return "No reservation or ticket found for this seat " + seat_num + ".";
    }
    else
    {
        if (seat_status != passenger_name)
        {
            return "This seat is reserved or bought by another passenger.";
        }
        // 取消座位的预定或售票信息
        int ind = find_seat_num_ind(plane, seat_num);
        strcpy(plane.table[ind].status, "AVAILABLE");
        return passenger_name + "Canceled seat" + seat_num + "successfully.";
    }
}

// 查询乘客预订/购买的座位
string Flights::check_passenger(string passenger_name)
{
    string result = "";

    // 遍历所有航班
    for (auto i = 0; i < f_cnt; i++)
    {
        Plane &plane = flights_seq[i];
        // cout << "checking plane: " << plane.plane_name << endl;
        // 遍历所有座位
        for (auto j = 0; j < MAXCNT; j++)
        {
            if (!strcmp(plane.table[j].status, "AVAILABLE"))
                continue;

            string seat_num = plane.table[j].seat_num;
            string seat_status = plane.table[j].status;
            string seat_passenger = plane.table[j].passenger_name;
            if (seat_passenger == passenger_name)
            {
                if (seat_status == "reserve")
                {
                    // 查询到乘客名义预定的座位
                    result += "Flight: " + string(plane.plane_name) + ", Seat: " + string(seat_num) + " (Reserved by) " + string(passenger_name);
                }
                else if (seat_status == "ticket")
                {
                    // 查询到乘客购买的座位
                    result += "Flight: " + string(plane.plane_name) + ", Seat: " + string(seat_num) + " (Ticket by) " + string(passenger_name);
                }
            }
        }
    }
    if (result == "")
        return "This passanger " + passenger_name + " does not reserve any seat or buy any ticket.";
    // 返回乘客预定和购买的座位信息
    return result;
}

void Flights::do_request(struct operation this_op, int wait_time)
{
    // TODO: 检查航班号是否存在，如果不存在就返回错误信息
    sleep(wait_time / INTERVAL);
    string msg;
    int i;
    for (i = 0; i < MAXSIZE; i++)
    {
        if (!strcmp(this_op.op_plane.data(), flights_seq[i].plane_name))
            break;
    };
    // 根据操作名称执行相应的操作
    if (this_op.op_func == "reserve")
    {
        cout << "\033[31m"
             << "Request:"
             << "\033[0m"
             << " Type:{reserve} Plane Name { " + this_op.op_plane + " } Seat{ " + this_op.op_seatnum + " } Passenger Name{ " + this_op.op_passenger_name + " }" << endl;
        // 调用预订座位函数
        msg = reserve_seat(flights_seq[i], this_op.op_seatnum, this_op.op_passenger_name);
    }
    else if (this_op.op_func == "ticket")
    {
        cout << "\033[31m"
             << "Request:"
             << "\033[0m"
             << " Type:{ticket} Plane Name { " + this_op.op_plane + " } Seat{ " + this_op.op_seatnum + " } Passenger Name{ " + this_op.op_passenger_name + " }" << endl;
        // 调用售票函数
        msg = sell_ticket(flights_seq[i], this_op.op_seatnum, this_op.op_passenger_name);
    }
    else if (this_op.op_func == "cancel")
    {
        cout << "\033[31m"
             << "Request:"
             << "\033[0m"
             << "Type:{cancel} Plane Name { " + this_op.op_plane + " } Seat{ " + this_op.op_seatnum + " } Passenger Name{ " + this_op.op_passenger_name + " }" << endl;
        // 调用取消预订函数
        msg = cancel_reservation(flights_seq[i], this_op.op_seatnum, this_op.op_passenger_name);
    }
    else if (this_op.op_func == "check_passenger")
    {
        cout << "\033[31m"
             << "Request:"
             << "\033[0m"
             << " Type:{check passenger} Passenger Name{ " + this_op.op_passenger_name + " }" << endl;
        // 调用查询乘客函数
        msg = check_passenger(this_op.op_passenger_name);
    }
    cout << "\033[32m"
         << "Log Info:"
         << "\033[0m"
         << " In plane " << this_op.op_plane + " " << msg + "\n"
         << endl;
}

int Agent::get_time_by_op_name(const string &op_name)
{
    if (op_name == "reserve")
        return reserve_time;
    else if (op_name == "ticket")
        return ticket_time;
    else if (op_name == "cancel")
        return cancel_time;
    else if (op_name == "check_passenger")
        return check_time;
    else
        return -1;
}

Agent::Agent()
{
    reserve_time = -1;
    ticket_time = -1;
    cancel_time = -1;
    check_time = -1;
}

// 读取文本文件的每一行
vector<string> readLinesFromFile(const string &filename)
{
    vector<string> lines;
    ifstream file(filename);
    if (file.is_open())
    {
        string line;
        while (getline(file, line))
        {
            lines.push_back(line);
        }
        file.close();
    }
    return lines;
}

// 解析并初始化飞机信息
int parseFlights(const vector<string> &lines, Plane *flight_seq)
{
    bool isFlightsSection = false;
    int cnt = 0;
    Plane plane;
    for (const string &line : lines)
    {
        if (line == "begin flights")
        {
            isFlightsSection = true;
        }
        else if (line == "end flights")
        {
            isFlightsSection = false;
        }
        else if (isFlightsSection)
        {
            stringstream ss(line);
            string plane_name, plane_num;
            int rows, seats_per_row;
            ss >> plane_name >> rows >> seats_per_row;

            plane = Plane();
            strcpy(plane.plane_name, plane_name.data());
            plane.col = seats_per_row;
            plane.row = rows;
            flight_seq[cnt++] = plane;
        }
    }
    return cnt;
}
// 解析并初始化代理信息
vector<Agent> parseAgents(const vector<string> &lines)
{
    vector<Agent> agents;        // 存储代理对象的容器
    bool isAgentSection = false; // 标志变量，用于确定当前是否处于代理部分的解析阶段
    Agent agent;                 // 当前代理对象

    for (const string &line : lines)
    {
        if (line == "begin agent")
        {
            isAgentSection = true;
            agent = Agent(); // 创建新的代理对象
        }
        else if (line == "end agent")
        {
            isAgentSection = false;
            agents.push_back(agent); // 完成代理信息解析，将代理对象添加到容器中
        }
        else if (isAgentSection)
        {
            stringstream ss(line);
            string command;
            ss >> command;
            struct operation temp_op; // 临时存储每个操作的细节

            if (command == "reserve")
            {
                if (agent.reserve_time == -1)
                    ss >> agent.reserve_time; // 解析并设置代理的延迟时间
                else
                {
                    temp_op.op_func = "reserve";
                    ss >> temp_op.op_plane >> temp_op.op_seatnum >> temp_op.op_passenger_name;
                    agent.op_seq.push_back(temp_op); // 将操作添加到代理对象的操作序列中
                }
            }
            else if (command == "ticket")
            {
                if (agent.ticket_time == -1)
                    ss >> agent.ticket_time; // 解析并设置代理的延迟时间
                else
                {
                    temp_op.op_func = "ticket";
                    ss >> temp_op.op_plane >> temp_op.op_seatnum >> temp_op.op_passenger_name;
                    agent.op_seq.push_back(temp_op); // 将操作添加到代理对象的操作序列中
                }
            }
            else if (command == "cancel")
            {
                if (agent.cancel_time == -1)
                    ss >> agent.cancel_time; // 解析并设置代理的延迟时间
                else
                {
                    temp_op.op_func = "cancel";
                    ss >> temp_op.op_plane >> temp_op.op_seatnum >> temp_op.op_passenger_name;
                    agent.op_seq.push_back(temp_op); // 将操作添加到代理对象的操作序列中
                }
            }
            else if (command == "check_passenger")
            {
                if (agent.check_time == -1)
                    ss >> agent.check_time; // 解析并设置代理的延迟时间
                else
                {
                    temp_op.op_func = "check_passenger";
                    temp_op.op_plane = "";
                    temp_op.op_seatnum = "";
                    ss >> temp_op.op_passenger_name;
                    agent.op_seq.push_back(temp_op); // 将操作添加到代理对象的操作序列中
                }
            }
        }
    }

    return agents; // 返回代理对象的容器
}

void Flights::show()
{
    cout << "\033[34m"
         << "Summary:"
         << "\033[0m" << endl;
    // // 遍历所有航班
    for (int i = 0; i < f_cnt; i++)
    {
        cout << "*******************************" << endl;
        Plane plane = flights_seq[i];
        cout << "Plane name: " << plane.plane_name << endl;

        //     // 遍历所有座位
        for (int i = 0; i < MAXCNT; i++)
        {
            // cout << plane.table[i].status << endl;
            if (strcmp(plane.table[i].status, "AVAILABLE") == 0)
                continue;
            string seat_num = plane.table[i].seat_num;
            string passenger_name = plane.table[i].passenger_name;
            string seat_status = plane.table[i].status;

            cout << "Seat: " << seat_num << ", Passenger: " << passenger_name << ", Status: " << seat_status << endl;
        }
    }
}